<template>
  <div>
    <div class="header-content" id="cst" v-if="state === 1">
      <img id="csc" src="@/assets/header/header-1.png" alt="" />
      <div class="header-cn">
        <h3 style="margin-right: -15px">学习</h3>
        <img src="@/assets/header/header-2.png" alt="" />
        <h3>分享</h3>
      </div>

      <div class="header-nav">
        <span class="el-dropdown-link">
          <router-link class="ab" to="/">首页</router-link>
        </span>
        <el-dropdown>
          <span class="el-dropdown-link">
            课程学习<i class="el-icon-arrow-down el-icon--right"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <a @click="HightCourse">高中课程</a>
            </el-dropdown-item>
            <el-dropdown-item
              ><a @click="UnCourse"> 大学课程</a></el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
        <span class="el-dropdown-link" v-if="managerid == 2"
          ><a @click="toMyBack"> 后台管理 </a></span
        >

        <span
          class="el-dropdown-link"
          v-if="teacherid == 3"
          @click="coursemanager"
        >
          课程管理
        </span>
        <el-drawer
          title="我的课程"
          :visible.sync="drawer"
          direction="rtl"
          size="50%"
        >
          <span>发布课程</span>
          <el-table
            :data="tableData"
            style="width: 100%"
            :row-class-name="tableRowClassName"
          >
            <el-table-column prop="coursename" label="课程名" width="180">
            </el-table-column>
            <el-table-column prop="coursetype" label="课程类型" width="180">
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="primary" @click="todetail(scope.row.coursename)"
                  >查看详情</el-button
                >
                <el-button type="danger" @click="deletecourse(scope.row.coursename)">删除</el-button>
              </template>
              
            </el-table-column>
          </el-table>

          <el-dialog title="上传课程" :visible.sync="dialogVisible" width="30%">
            <el-form ref="form" :model="form" label-width="80px">
              <el-form-item label="课程描述">
                <el-input v-model="form.listname"></el-input>
              </el-form-item>
              <el-form-item label="课程名称">
                <el-input v-model="form.name"></el-input>
              </el-form-item>
            </el-form>
            <el-upload
              class="upload-demo"
              id="filepath"
              action="http://localhost:81/teacher/upcoursev"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
              :on-change="handlechange"
              name="tvFile"
              multiple
              :limit="3"
            >
              <el-button class="ssccourse" type="primary">选择视频</el-button>
            </el-upload>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button @click="sureuptv">确 定</el-button>
            </span>
          </el-dialog>
          <el-button type="text" class="sccourse" @click="dialogVisible = true"
            >上传课程</el-button
          >
        </el-drawer>

        <el-dropdown v-show="roles != null && roles.length > 0">
          <span class="el-dropdown-link"> 欢迎{{ user.username }} </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              ><a @click="tousercenter">个人中心</a></el-dropdown-item
            >
            <el-dropdown-item
              ><a @click="toteacherregist">教师认证</a></el-dropdown-item
            >
            <el-dropdown-item
              ><a @click="tocollectcourse">收藏课程</a></el-dropdown-item
            >
            <el-dropdown-item
              ><a @click="loginOut">退出登录</a></el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
        <span
          class="el-dropdown-link"
          style="margin-right: -15px"
          @click="toLogin"
          v-if="roles == null || roles.length <= 0"
        >
          登录
        </span>
        <span
          class="el-dropdown-link"
          v-if="roles == null || roles.length <= 0"
          @click="roRegist"
        >
          注册
        </span>
      </div>
    </div>
    <div class="content">
      <component
        :is="comName"
        @fhindex="getLogin"
        :lorsta="loginName"
        @singleCourse="getSingleCourse"
        :coursename="coursename"
        :username="user.username"
        @tfn="toStart"
      ></component>
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import Lunbo from './ins/Lunbo.vue'
import Login from '@/components/ins/Login.vue'
import Hight from './course/Hight.vue'
import SingleHCourse from './course/SingleHCourse.vue'
import UnCourse from './course/UnCourse.vue'
import MyBack from '@/components/back/MyBack.vue'
import Usercenter from './user/Usercenter.vue'
import Teacherregit from './userteacher/Teacherregit.vue'
import CollecCourse from './userteacher/CollecCourse.vue'
import bus from './eventBus'
export default {
  data() {
    return {
      state: 1,
      comName: 'Lunbo',
      loginName: '',
      user: {
        username: '',
      },
      roles: [],
      userid: '',
      managerid: '',
      teacherid: '',
      coursename: '',

      drawer: false, //抽屉是否打开
      tableData: [],
      dialogVisible: false,
      form: {
        name: '',
        listname: '',
      },
      filename: '',
    }
  },
  methods: {
    //高中课程
    HightCourse() {
      // this.comName = 'Hight'
      this.$router.push('/hcourse/' + this.user.username)
      // document.getElementById('csc').style.height = '100px'
      // document.getElementById('cst').style.backgroundColor = '#eee'
    },
    //大学课程
    UnCourse() {
      this.$router.push('/uncourse/' + this.user.username)
      // this.comName = 'UnCourse'
      // document.getElementById('csc').style.height = '100px'
      // document.getElementById('cst').style.backgroundColor = '#eee'
    },
    //教师认证
    toteacherregist() {
      // this.comName = 'Teacherregit'
      // document.getElementById('csc').style.height = '100px'
      this.$router.push('/teacherregist/' + this.user.username)
    },
    //收藏课程
    tocollectcourse() {
      this.comName = 'CollecCourse'
      document.getElementById('csc').style.height = '100px'
      // this.$router.push('/collectcourse/' + this.user.username)
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return 'warning-row'
      } else if (rowIndex === 3) {
        return 'success-row'
      }
      return ''
    },
    // 课程管理
    async coursemanager() {
      const that = this
      that.drawer = true
      const { data: res } = await axios.get(
        'http://localhost:81/teacher/getMyCourse',
        {
          params: {
            username: that.user.username,
          },
        }
      )
      console.log('查询到发布的课程', res)
      if (res.code == 200) {
        that.tableData = res.data
      } else {
        that.$message.error(res.msg)
      }
    },
    // 上传课程
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      console.log('上传完后视频名', res)
      this.filename = res.data
    },
    beforeAvatarUpload(file) {
      var that = this
      console.log('文件', file)
      var fileObj = document.getElementById("filepath").files
      console.log("文件路径"+fileObj)
      // 获取后缀名
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const isLt2M = file.size / 1024 / 1024 < 500
      const isLtType = [
        'video/mp4',
        'video/ogg',
        'video/flv',
        'video/avi',
        'video/wmv',
        'video/rmvb',
        'video/mov',
      ]

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 500M!')
      }
      let correctType = true
      // 限制视频格式
      if (isLtType.indexOf(file.type) == -1) {
        correctType = false
        this.$message.warning('请上传视频文件')
      } else {
        correctType = true
      }

      // 获取视频时长
      let url = URL.createObjectURL(file)
      let audioElement = new Audio(url)
      let duration
      let fun = (duration) => {
        this.duration = duration
      }
      audioElement.addEventListener('loadedmetadata', function () {
        duration = audioElement.duration //以秒为单位
        fun(parseFloat(duration).toFixed(1))
      })

      return isLt2M && correctType
    },
    handlechange(file, fileList){
      console.log("111",file)
      console.log("222",fileList)
      console.log("333",URL.createObjectURL(file.raw))
      console.log("444",document.getElementById("filepath").value)

    },
    // 查看课程详情
    async todetail(coursename) {
      console.log("详情参数",coursename);
      this.$router.push("/coursedetail/" + coursename)
    },
    // 删除课程
    deletecourse(coursename){

    },
    //返回首页
    toStart() {
      this.comName = 'Lunbo'
      document.getElementById('csc').style.height = '500px'
      document.getElementById('cst').style.backgroundColor = '#rgb(255,255,255)'
    },
    async start() {
      const { data: res } = await axios.get(
        'http://localhost:81/checkCode/queryStatus',
        {
          params: {
            token: localStorage.getItem('token'),
          },
        }
      )
      if (res.data == null) {
        console.log('未登录')
      } else {
        console.log('用户名', res.data.username)
        this.user.username = res.data.username
        this.getRole()
      }
    },
    async getRole() {
      const { data: re } = await axios.get(
        'http://localhost:81/checkCode/queryRole?username=' + this.user.username
      )
      console.log('查询用户角色', re.data)
      this.roles = re.data
      const user = re.data.filter((item) => item.id == 1)

      if (user != null && user.length > 0) {
        this.userid = user[0].id
      }
      const manager = re.data.filter((item) => item.id == 2)
      if (manager != null && manager.length > 0) {
        this.managerid = manager[0].id
      }

      const teacher = re.data.filter((item) => item.id == 3)
      if (teacher != null && teacher.length > 0) {
        this.teacherid = teacher[0].id
      }

      console.log('最终', this.managerid, this.teacherid)
    },
    async loginOut() {
      const { data: res } = await axios({
        method: 'GET',
        url:
          'http://localhost:81/user/loginOunt?username=' + this.user.username,
      })
      localStorage.removeItem('token')
      this.roles = ''
      this.userid = ''
      this.managerid = ''
      this.teacherid = ''
      console.log('退出登录后', this.roles)
    },
    //到登录页
    toLogin() {
      // this.comName = 'Login'
      // this.loginName = 'Loginin'
      // this.state = 0
      this.$router.push('/login/' + 'Loginin')
    },
    //管理页
    toMyBack() {
      // this.comName = 'MyBack'
      // this.state = 0
      this.$router.push('/myback')
    },
    //个人中心
    tousercenter() {
      // this.comName = 'Usercenter'
      // this.state = 0
      const that = this
      this.$router.push('/usercenter/' + that.user.username)
    },

    //学习课程
    getSingleCourse(val) {
      console.log('获得学习课程数据', val)
      if (val.coursename == 'javaweb') {
        this.$message.warning('该课程尚未建评论表')
        return
      }
      this.comName = val.comName
      this.coursename = val.coursename
    },

    // 确定上传视频
    async sureuptv() {
      console.log('上传视频数据', this.form)
      console.log('视频名', this.filename)
      const { data: res } = await axios.get(
        'http://localhost:81/teacher/upCourse',
        {
          params: {
            listname: this.form.listname,
            coursename: this.form.name,
            mvname: this.filename,
          },
        }
      )
      if (res.code == 200) {
        this.dialogVisible = false
        this.form = {}
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.data.msg)
      }
    },
    //登录返回
    getLogin(val) {
      console.log('登录返回主界面', val)
      if (val != null) {
        this.state = 1
        this.comName = 'Lunbo'
        console.log('重新获取登录状态')
        this.start()
      }
    },
    //到注册页
    roRegist() {
      // this.loginName = 'Registin'
      // this.comName = 'Login'
      // this.state = 0
      this.$router.push('/login/' + 'Registin')
    },
  },

  created() {
    this.start()
    bus.$on('mlogout', (val) => {
      console.log('管理退出登录', val)
      if (val != null) {
        this.state = 1
        this.comName = 'Lunbo'
        this.roles = ''
        this.userid = ''
        this.managerid = ''
        this.teacherid = ''
      }
    })
  },
  components: {
    Lunbo,
    Login,
    Hight,
    SingleHCourse,
    UnCourse,
    MyBack,
    Usercenter,
    Teacherregit,
    CollecCourse,
  },
}
</script>

<style lang="less" scoped>
.header-content {
  min-height: 300px;
  position: relative;
  display: flex;
  img {
    width: 90%;
    margin-left: 5%;
    margin-top: 10px;
    border-radius: 10px 10px 0 0;
  }
}
.header-cn {
  display: flex;
  img {
    width: 50px;
    height: 50px;
    margin-top: 20px;
  }
  h3 {
    width: 50px;
    height: 50px;
    line-height: 50px;
    padding: 0 5px;
  }
  position: absolute;
  top: 25px;
  left: 10%;
  color: rgb(255, 255, 255);
}
.header-nav {
  display: flex;
  position: absolute;
  top: 50px;
  right: 10%;
}

.el-dropdown-link {
  cursor: pointer;
  color: rgb(255, 255, 255);
  font-size: 20px;
  margin: 0 25px;
  .ab {
    color: rgb(255, 255, 255);
    text-decoration: none;
  }
}
.el-icon-arrow-down {
  font-size: 12px;
}
.content {
  display: flex;
  margin-top: 100px;
  margin-left: 80px;
}
.sccourse {
  position: absolute;
  bottom: 20px;
  left: 50%;
}
.ssccourse {
  position: absolute;
  bottom: 20px;
  left: 30%;
}
</style>
